package com.android.kotlincoroutinemvvmdemo.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.android.kotlincoroutinemvvmdemo.R

class ShadowLayerView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null) : View(context, attributeSet) {

    private val mPaint by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            color = context.resources.getColor(R.color.black)
            textSize = context.resources.getDimension(R.dimen.sp_20)
        }
    }

    private var mWidth = 0
    private var mHeight = 0

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        mWidth = when (MeasureSpec.getMode(widthMeasureSpec)) {
            MeasureSpec.EXACTLY -> {
                MeasureSpec.getSize(widthMeasureSpec)
            }
            else -> {
               context.resources.getDimension(R.dimen.dp_100).toInt()
            }
        } - paddingStart - paddingEnd

        mHeight = when (MeasureSpec.getMode(heightMeasureSpec)) {
            MeasureSpec.EXACTLY -> {
                MeasureSpec.getSize(heightMeasureSpec)
            }
            else -> {
                context.resources.getDimension(R.dimen.dp_100).toInt()
            }
        } - paddingTop - paddingBottom

        setMeasuredDimension(mWidth, mHeight)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.apply {
            //设置文字的倾斜度
            mPaint.textSkewX = -1.5f
            //radius是阴影的模糊范围;dx dy是阴影的偏移量;shadowColor是阴影的颜色.
            mPaint.setShadowLayer(10f, 0f, 0f, Color.RED)
            val contentWidth = mPaint.measureText(content, 0, content.length)
            //高度居中
            val fontMetrics = mPaint.fontMetrics
            val fontHeight = fontMetrics.bottom - fontMetrics.top
            val textY = mHeight - (mHeight - fontHeight) / 2.0f - fontMetrics.bottom + 0.5f
            //水平居中
            val textX = (mWidth - contentWidth) / 2.0f + 0.5f
            drawText(content, textX, textY, mPaint)
        }
    }

    companion object {
        const val content = "Hello ShadowLayerView"
    }
}